package com.liaowei.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liaowei.common.BaseResponse;
import com.liaowei.common.Constants;
import com.liaowei.common.ErrorCode;
import com.liaowei.exception.CustomerException;
import com.liaowei.model.domain.Post;
import com.liaowei.model.domain.UserPostHistory;
import com.liaowei.model.param.PostHistoryParam;
import com.liaowei.user.mapper.UserPostHistoryMapper;
import com.liaowei.user.model.param.PagePostHistoryParam;
import com.liaowei.user.openfeign.PostClient;
import com.liaowei.user.service.UserPostHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
* @author LindaMan
* @description 针对表【wy_user_post_history(用户浏览帖子历史表)】的数据库操作Service实现
* @createDate 2023-05-01 17:19:40
*/
@Service
@RequiredArgsConstructor
public class UserPostHistoryServiceImpl extends ServiceImpl<UserPostHistoryMapper, UserPostHistory>
    implements UserPostHistoryService{

    private final UserPostHistoryMapper userPostHistoryMapper;
    private final PostClient postClient;


    // 校验用户是否认证
    public void matchUser(Long userId,Long loginId){
        if (!loginId.equals(userId)){
            throw new CustomerException(Constants.PARAM_ERROR,"请先认证");
        }
    }

    /**
     * 根据userId删除全部的帖子历史记录
     * @param userId 用户id
     * @return 提示信息
     */
    @Override
    public String removeAllPostHistoryByUserId(long userId) {
        long loginId = StpUtil.getLoginIdAsLong();
        // 检查用户是否合法
        matchUser(userId,loginId);

        // 删除历史记录
        try {
            LambdaQueryWrapper<UserPostHistory> wrapper = Wrappers.lambdaQuery(UserPostHistory.class)
                    .eq(UserPostHistory::getUserId, userId);
            userPostHistoryMapper.delete(wrapper);
        } catch (Exception e) {
            throw new CustomerException(ErrorCode.SYSTEM_ERROR);
        }

        return "删除成功";
    }

    /**
     * 分页查询自己的帖子历史记录
     * @param historyParam 帖子历史参数
     * @return List<Post> 帖子列表
     */
    @Override
    public List<Post> searchPostHistoryPage(PagePostHistoryParam historyParam) {
        Long userId = historyParam.getUserId(); // 获取用户id
        Long loginId =  Long.parseLong(StpUtil.getLoginId().toString()); // 获取当前认证的id
        // 检查是否认证
        matchUser(userId,loginId);

        // 分页参数预处理
        int pageNum = historyParam.getPageParam().getPageNum();
        int pageSize = historyParam.getPageParam().getPageSize();
        pageNum = (pageNum - 1) * pageSize;

        // 根据用户id分页查询浏览的文章id列表
        List<Long> postIdList = userPostHistoryMapper.selectPostIdsByUserId(userId,pageNum,pageSize);

        // 根据文章id列表分页查询文章列表
        List<Post> result = new ArrayList<>();
        if (postIdList.size() > 0){
            BaseResponse<List<Post>> response = postClient.pageByIds(postIdList);
            if (response.getCode() != 1){
                throw new CustomerException(ErrorCode.SYSTEM_ERROR);
            }else {
                result = response.getData();
            }
        }

        return result;
    }

    /**
     * 根据用户id和帖子id删除帖子记录
     * @param userId 用户id
     * @param postId 帖子id
     * @return 提示信息
     */
    @Transactional
    @Override
    public String removePostHistoryByUserIdAndPostId(Long userId, Long postId) {
        // 获取当前认证的id
        Long loginId =  Long.parseLong(StpUtil.getLoginId().toString());

        // 检查当前用户是否是合法用户
        matchUser(userId,loginId);

        // 删除记录
        LambdaUpdateWrapper<UserPostHistory> wrapper = Wrappers.lambdaUpdate(UserPostHistory.class)
                .eq(UserPostHistory::getUserId, userId)
                .eq(UserPostHistory::getPostId, postId);
        try {
            userPostHistoryMapper.delete(wrapper);
        }catch (Exception e){
            throw new CustomerException(ErrorCode.SYSTEM_ERROR);
        }

        return "删除成功";
    }

    /**
     * 新增帖子历史记录
     * @param postHistoryParam 新增帖子历史记录参数
     * @return 提示信息
     */
    @Transactional
    @Override
    public String addPostHistory(PostHistoryParam postHistoryParam) {
        // 获取当前认证的id
        Long loginId =  Long.parseLong(StpUtil.getLoginId().toString());
        // 获取当前用户id
        Long userId = postHistoryParam.getUserId();
        Long postId = postHistoryParam.getPostId();

        // 检查当前用户是否是合法用户
        matchUser(userId,loginId);

        // 检查帖子是否存在
        BaseResponse<Post> response = postClient.postVoById(postId);
        if (response.getCode() != 1){
            throw new CustomerException(Constants.PARAM_ERROR,"帖子不存在");
        }

        // 新增历史记录
        UserPostHistory history = new UserPostHistory();
        history.setUserId(userId);
        history.setPostId(postId);
        try {
            userPostHistoryMapper.insert(history);
        } catch (Exception e) {
            throw new CustomerException(ErrorCode.SYSTEM_ERROR);
        }

        return "新增成功";
    }
}




